package com.aop;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.constants.Constants;
import com.crmeb.core.utils.RedisUtil;
import com.github.pagehelper.util.StringUtil;
import com.utils.CrmebUtil;
import com.zbkj.crmeb.authorization.model.TokenModel;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;

import lombok.extern.slf4j.Slf4j;

/**
 * 请求拦截
 * @author daigb
 * @date:  2021-12-10 10:20
 */
@Slf4j
@Aspect
@Configuration
public class ControllerAspect {
    @Autowired
    protected RedisUtil redisUtil;
    @Autowired
    private UserService userService;

	@Around("execution(* com.zbkj.crmeb..*Controller.*(..))")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        Object returnValue = null;
        final List<Object> params = new ArrayList<>();
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        
        // 当前用户
        Object adminId = null;
        String userType = "后端";
        String token = request.getParameter(Constants.HEADER_AUTHORIZATION_KEY);
        if(StringUtil.isEmpty(token)){
        	token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);
        }
        if(StringUtil.isNotEmpty(token)) {
            adminId = redisUtil.get(TokenModel.TOKEN_REDIS + token);
        }
        if(null == adminId) {
        	User user = userService.getInfo();
        	adminId = null != user ? user.getUid() : null;
            userType = "前端";
        }
        
        Object[] args = point.getArgs();
        for (int i = 0; i < args.length; i++) {
            Object object = args[i];
            // 过滤非可获取类型
            if (object instanceof HttpServletResponse) {
                continue;
            }
            if (object instanceof HttpServletRequest) {
                continue;
            }
            params.add(object);
        }
        try {
			log.info("--------------- 当前ip: {} 收到{} 请求: {} ---------------", CrmebUtil.getClientIp(request), request.getMethod(), request.getRequestURL().toString());
			String cloneParams = JSONObject.toJSONString(params);
			log.info("--------------- {}用户: {} 请求参数: {} ---------------", userType, adminId, cloneParams);
		} catch (Exception e1) {
			log.info("--------------- 请求参数非json对象 ---------------");
		}
        Long startTime = System.currentTimeMillis();
        try {
            returnValue = point.proceed(point.getArgs());
        } catch (Exception e) {
        	returnValue = e.toString();
			throw e;
        }
        Long endTime = System.currentTimeMillis();
        log.info("--------------- 接口: {} 耗时: {}毫秒 ---------------", request.getRequestURI(), endTime - startTime);

        return returnValue;
    }
    
}